import { reactive, toRefs, computed, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/utils/node-http'

export function usePageList(options = {}) {
  const route = useRoute()
  const router = useRouter()

  const query = { ...route.query, ...options.query }

  // const state = reactive({
  //   // 面包屑
  //   breadcrumb: route.meta.breadcrumb || [],

  //   // 总条数
  //   total: 0,

  //   // 当前页数
  //   page: options.page || route.query.page || 1,

  //   // 每页条数
  //   pageSize: options.pageSize || route.query.pageSize || 20,

  //   // 所选数据
  //   selectData: [],

  //   // 加载中
  //   loading: false,

  //   // 主键
  //   key: options.key || route.meta.key || 'id',

  //   // 列表数据
  //   data: [],

  //   // Api
  //   api: options.api || route.meta.api,

  //   model: '',

  //   // 查询参数
  //   query: query,

  //   // 默认查询参数(重置用)
  //   defaultQuery: query,

  //   shwoEdit: false,

  //   detail: null,
  // })

  class PageEdit {
    constructor(options = {}) {
      // Object.keys(state).map(key => {
      //   this[key] = state[key]
      // })

      const route = (this.$route = useRoute())
      this.$router = useRouter()

      const query = { ...route.query, ...options.query }

      this.breadcrumb = ref(route.meta.breadcrumb || []) // 面包屑
      this.total = ref(0) // 总条数
      this.page = ref(options.page || route.query.page || 1) // 当前页数
      this.pageSize = ref(options.pageSize || route.query.pageSize || 20) // 每页条数
      this.selectData = ref([]) // 所选数据
      this.loading = ref(false) // 加载中
      this.key = ref(options.key || route.meta.key || 'id')
      this.data = reactive([]) // 列表数据
      this.api = ref(options.api || route.meta.api) // API
      this.query = reactive(query) // 查询参数
      this.defaultQuery = { ...query } // 默认查询参数(重置用)
      this.shwoEdit = false
      this.detail = null

      this.selectd = computed(() => this.selectData && this.selectData.length)

      this.init()
    }

    /**
     * 初始化
     * @param {}} options
     */
    init(options = {}) {
      this.getData()
    }

    /**
     * 刷新
     */
    handleRefresh() {
      this.getData()
    }

    /**
     * 获取数据
     */
    getData(config = {}) {
      this.loading.value = true

      // 后台使用
      http({
        url: this.api.value,
        params: {
          // page: this.page,
          // pageSize: this.pageSize,
          // ...this.query,
        },
        // ...config,
      })
        .then((res) => {
          this.data = res.list
          this.total = res.total
          this.page = res.page
          this.pageSize = res.pageSize
        })
        .finally(() => {
          this.loading.value = false
        })
    }

    // 删除
    handleDelete(item) {
      ElMessageBox.confirm('确认删除?', '提示', {
        type: 'warning',
      }).then(() => {
        const id = item[this.key]
        http.delete(`${this.api}/${id}`).then((res) => {
          ElMessage.success('删除成功')
          this.handleRefresh()
        })
      })
    }

    /**
     * 修改操作
     * @param {Object} item 修改的行数据
     * @param {Object} newItem 修改字段组成的对象
     * @param {String} confirmMsg 确认提示语
     * @param {String} successMsg 请求完成提示语
     */
    async handleUpdate(item, newItem, confirmMsg, successMsg) {
      if (confirmMsg) {
        await ElMessageBox.confirm(confirmMsg, '提示', {
          type: 'warning',
        })
      }

      http.put(`${this.api}/${item[this.key]}`, newItem).then((res) => {
        ElMessage.success(successMsg || '操作成功')
        this.handleRefresh()
      })
    }

    /**
     * 当选择项发生变化时会触发该事件
     * @param {Array}  selection
     */
    handleSelectionChange(val) {
      this.selectData = val
    }

    // 批量删除
    handleBatchDelete(successMsg) {
      const idList = this.selectData.map((item) => item[this.key])
      if (!idList || !idList.length) returnElMessage.warning('请先选择数据')

      ElMessageBox.confirm('确认批量删除?', '警告', {
        type: 'warning',
      }).then((res) => {
        http.delete(`${this.api}/${idList.join(',')}`).then((res) => {
          ElMessage.success(successMsg || '删除成功')
          this.handleRefresh()
        })
      })
    }

    // 批量修改
    handleBatchUpdate(newData, confirm, successMsg) {
      const idList = this.selectData.map((item) => item[this.key])
      if (!idList || !idList.length) returnElMessage.warning('请先选择数据')

      ElMessageBox.confirm(confirm || '确认操作?', '警告', {
        type: 'warning',
      }).then((res) => {
        http.put(`${this.api}/${idList.join(',')}`, newData).then((res) => {
          ElMessage.success(successMsg || '操作成功')
          this.handleRefresh()
        })
      })
    }

    /**
     * 搜索
     */
    handleSearch() {
      this.page.value = 1
      this.total.value = 0

      this.setPageUrl({
        ...this.query,
        page: this.page.value,
        pageSize: this.pageSize.value,
      })

      this.handleRefresh()
    }

    /**
     * 重置
     */
    handleReset(isSearch = true) {
      const query = {
        ...this.defaultQuery,
      }

      this.emptyQuery()
      this.setPageUrl(query)
      if (isSearch) this.handleRefresh()
    }

    /**
     * 清空this.query
     */
    emptyQuery() {
      Object.keys(this.query).map((key) => {
        delete this.query[key]
      })
    }
    /**
     * 设置this.query
     */
    setQuery(query) {
      Object.keys(query).map((key) => {
        this.query[key] = query[key]
      })
    }

    /**
     * 设置URL参数
     */
    setPageUrl(query) {
      this.setQuery(query)
      this.$router.replace({
        path: this.$route.path,
        query,
      })
    }

    // 分页切换
    appHandlePageChange(page) {
      this.page.value = page

      this.setPageUrl()
      this.handleRefresh()
    }

    // 条数切换
    appHandleSizeChange(pageSize) {
      this.page.value = 1
      this.pageSize.value = pageSize

      this.setPageUrl()
      this.handleRefresh()
    }

    // 新增
    handleAdd() {
      this.shwoEdit.value = true
      this.detail = {}
    }

    handleEdit(item) {
      this.shwoEdit.value = true
      this.detail = item
    }
  }

  return new PageEdit()

  // const temp = {
  //   data: reactive([]),
  //   query: reactive({}),
  //   title: ref('title')
  // }

  // return {
  //   // ...toRefs(temp)
  //   title: ref('title')
  // }
}
